/**
 * 
 */
package io.gitee.falllee.dao.core.table;

import java.util.List;

import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

import io.gitee.falllee.dao.cache.DataCache;
import io.gitee.falllee.dao.config.DaoConfigContextHolder;
import io.gitee.falllee.dao.enums.EnableConfigEnum;
import io.gitee.falllee.dao.model.BaseDaoConfig;

/**
 * @author batty
 * @date 2022-06-27
 *
 */
public class CacheBuilder {

    private DataCache dataCache;
    
    private BaseDaoConfig daoConfig;
    
    private String tableName;
    
    private Integer cache;
    
    CacheBuilder(TableBuilder parent) {
        this.dataCache = parent.getDataCache();
        this.daoConfig = parent.getDaoConfig();
        this.tableName = parent.getTableName();
        this.cache = parent.getCache();
    }
    
    public void clearCache() {
        if (enableCache()) {
            dataCache.delTable(tableName);
        }
    }

    public void clearCache(@Nullable Object keyValue) {
        if (enableCache()) {
            // 清除实体列表缓存
            dataCache.delTableList(tableName);
            if (keyValue != null) {
                dataCache.delTableByKeyValue(keyValue, tableName);
            }
        }
    }

    public void clearCache(@Nullable List<? extends Object> keyValueList) {
        if (enableCache()) {
            // 清除实体列表缓存
            dataCache.delTableList(tableName);
            if (!CollectionUtils.isEmpty(keyValueList)) {
                dataCache.delTableByKeyValueList(keyValueList, tableName);
            }
        }
    }
    
    boolean enableCache() {
        if (DaoConfigContextHolder.getDisableCache()) {
            return false;
        }
        if (EnableConfigEnum.ENABLE.getConfig().equals(cache)) {
            return true;
        } else if (EnableConfigEnum.DISABLE.getConfig().equals(cache)) {
            return false;
        }
        if (EnableConfigEnum.ENABLE.getConfig().equals(daoConfig.getEnableCache())) {
            return true;
        } else if (EnableConfigEnum.DISABLE.getConfig().equals(daoConfig.getEnableCache())) {
            return false;
        }
        return false;
    }
}
